package edu.buaa.resourceManager.controller;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import edu.buaa.resourceManager.helper.Utils;
import edu.buaa.resourceManager.search.Search;
import edu.buaa.resourceManager.store.StoreDB;
import edu.buaa.resourceManager.vo.CustomProperty;
import edu.buaa.resourceManager.vo.FileEntity;
import edu.buaa.resourceManager.vo.ResourcePath;
import org.slf4j.Logger;
import spark.Route;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * Created by song on 17-6-22.
 */
public class PathController
{
    private static Logger log = Utils.getDevLogger();
    private static JsonParser parser = new JsonParser();

    public static Route Page = (request, response) -> {
        for(String s:request.splat()){
            log.trace(s);
        }
        response.type("text/html");
        return new Scanner(ImportController.class.getResourceAsStream("/html/FileInfo.html"), "UTF-8").useDelimiter("\\A").next();
    };

//    public static Route fetchFileJson = (request, response) -> {
//        String sha512 = request.params(":sha512");
//FIXME        ResourcePath file = StoreDB.getInstance().getFileBySha512(sha512);
//        response.type("application/json");
//        return JsonStore.getInstance().json.toJson(file);
//    };

    public static Route NewPathWithEntity = (request, response) -> {
        log.debug("createNewFile");
        log.trace(request.body());
        JsonObject obj = parser.parse(request.body()).getAsJsonObject();
        ResourcePath resourcePath = new ResourcePath();
        FileEntity entity = new FileEntity();
        List<CustomProperty> properties = new ArrayList<>();
        String time = Utils.timestamp2Str(System.currentTimeMillis());
        for(Map.Entry<String, JsonElement> pair : obj.entrySet()){
            String key = pair.getKey();
            JsonElement value = pair.getValue();
            switch(key){
                case "path":
                    resourcePath.setPath(value.getAsString());
                    break;
                case "comment":
                    entity.setComment(value.getAsString());
                    break;
                case "createTime":
                    entity.setCreateTime(new java.sql.Date(value.getAsLong()));
                    break;
                case "lastModifiedTime":
                    entity.setLastModifiedTime(new java.sql.Date(value.getAsLong()));
                    break;
                case "size":
                    entity.setSize(value.getAsLong());
                    break;
                case "sha512":
                    entity.setSha512(value.getAsString());
                    break;
                case "md5head":
                    entity.setHeadMd5(value.getAsString());
                    break;
                case "relFiles":
                    JsonArray files = pair.getValue().getAsJsonArray();
                    for(JsonElement file : files){
                        ResourcePath rf = new ResourcePath();
                        String fileName = file.getAsString();
                        rf.setPath(fileName);
                        rf.setOnline(false);
                        rf.setMetaUpdateTime(new java.sql.Date(System.currentTimeMillis()));
                        rf.setComment("Auto import (at "+time+") together with:\n"+resourcePath.getPath());
                        resourcePath.addRelFile(rf);
                    }
                    break;
                default:
                    properties.add(new CustomProperty(key, value.getAsString()));
            }
        }

        entity.setProperties(properties);
        resourcePath.setOnline(true);
        resourcePath.setFileEntity(entity);

        StoreDB.getInstance().importPathWithEntity(resourcePath);
        Search.getInstance().addDoc(resourcePath);
//        JsonStore.getInstance().saveOrUpdate(new File(resourcePath.getPath()), resourcePath);
//
        return "success";
    };

    //    private static Route updateFile = (request, response) -> {
//        log.debug("updateFile");
//        JsonObject obj = parser.parse(request.body()).getAsJsonObject();
//        ResourcePath resourceFile = new ResourcePath();
//        for(Map.Entry<String, JsonElement> pair : obj.entrySet()){
//            String key = pair.getKey();
//            JsonElement value = pair.getValue();
//            switch(key){
//                case "createTime":
//                case "lastModifiedTime":
//                case "size":
//                case "sha512":
//                case "md5head":
//                case "dependFiles":
//                    break;
//                case "path":
//                    resourceFile.setPath(value.getAsString());
//                    break;
//                case "hash":
//                    resourceFile.setHash(value.getAsString());
//                    break;
//                case "comment":
//                    resourceFile.setComment(value.getAsString());
//                    break;
//                default:
//                    resourceFile.getProperties().add(new CustomProperty(key, value.getAsString()));
//            }
//        }
//
//        StoreDB.getInstance().createOrUpdateFile(resourceFile);
//        Search.getInstance().updateDoc(resourceFile);
//        JsonStore.getInstance().saveOrUpdate(new File(resourceFile.getPath()), resourceFile);
//
//        return "success";
//    };

//    private static ResourcePath getResourceFileInfo(String fileName, String fromPath) {
//        File f = new File(fileName);
//        ResourcePath rf = new ResourcePath(f);
//        rf.setOnline(f.exists() && !f.isDirectory());
//        if(rf.isOnline()){
//            rf.setComment("[AUTO]");
//            rf.setPath(f.getAbsolutePath());
//            rf.setSize(f.length());
//            try {
//                rf.setHash(com.google.common.io.Files.hash(f, Hashing.sha512()).toString());
//                if(rf.getSize()>=10*1024*1024) {
//                    rf.setHeadMd5(Utils.getFileHeadMd5(f));
//                }else{
//                    rf.setHeadMd5("");
//                }
//                BasicFileAttributes attr = Files.readAttributes(f.toPath(), BasicFileAttributes.class);
//                rf.setCreateTime(new Date(attr.creationTime().toMillis()));
//                rf.setLastModifiedTime(new Date(attr.lastModifiedTime().toMillis()));
//                return rf;
//            } catch (IOException ignore) {
//                log.warn("auto add failed: "+fileName+" from("+fromPath+"), switch to off line", ignore);
//                rf.setOnline(false);
//                return rf;
//            }
//        }else{
//            return rf;
//        }
//    }
}
